package com.weituotian.system.controller;

import com.weituotian.core.controller.BaseController;
import com.weituotian.core.exception.ControllerException;
import com.weituotian.core.exception.ServiceException;
import com.weituotian.core.result.Option;
import com.weituotian.core.utils.PageInfo;
import com.weituotian.system.entity.User;
import com.weituotian.system.entity.enums.OpenState;
import com.weituotian.system.entity.enums.UserType;
import com.weituotian.system.service.IRoleService;
import com.weituotian.system.service.IUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 */
@Controller("userController")
@RequestMapping("${systemPath}/user")
public class UserController extends BaseController {

    private final IUserService userService;

    private final IRoleService roleService;

    @Autowired
    public UserController(IUserService userService, IRoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }

    @ModelAttribute
    public void initUrl(Model model) {
        String contextPath = this.getContextPath();
        model.addAttribute("edit_url", contextPath + systemPath + "/user/edit");
        model.addAttribute("add_url", contextPath + systemPath + "/user/add");
        model.addAttribute("delete_url", contextPath + systemPath + "/user/delete");

        model.addAttribute("grant_url", contextPath + systemPath + "/user/grant");
        model.addAttribute("dogrant_url", contextPath + systemPath + "/user/dogrant");

    }

    @RequestMapping(value = "/")
    public String index() {
        return "system/index";
    }

    /**
     * 用户列表
     *
     * @param page 当前页数
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(Integer page, Integer pagesize, Model model) {
        PageInfo<User> pageInfo = new PageInfo<>(page, 10);

        pageInfo.setCondition(getSearchMap());

        //查询用户列表,结果都保存在pageinfo里面了
        userService.findPage(pageInfo);

        //返回视图
        model.addAttribute("pageinfo", pageInfo);


        model.addAttribute("pageName", "用户列表");

        return "system/user/index";
    }

    /**
     * 增加页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/add")
    public String add(Model model) {
        User user = new User();

        model.addAttribute("user", user);
        model.addAttribute("openStatus", OpenState.values());

        model.addAttribute("form_url", this.getContextPath() + systemPath + "/user/doadd");
        model.addAttribute("action", "add");
        model.addAttribute("pageName", "用户新增");


        return "system/user/edit";
    }

    /**
     * 处理增加用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/doadd", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object doadd(User user) {

        //密码
        String pwd = user.getPassword();
        if (pwd != null && !StringUtils.isBlank(pwd)) {
            user.setPassword(DigestUtils.md5Hex(pwd));//md5密码加密
        }

        try {
            userService.add(user);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("增加成功!");
    }

    /**
     * 编辑页面
     *
     * @return
     */
    @RequestMapping(value = "/edit")
    public String edit(Integer id, Model model) {
        User user = userService.findById(id);

        //返回视图
        model.addAttribute("user", user);
        model.addAttribute("openStatus", OpenState.values());
        model.addAttribute("userTypes", UserType.values());// userService.getOpenStatus()

        model.addAttribute("form_url", this.getContextPath() + systemPath + "/user/doedit");
        model.addAttribute("action", "edit");
        model.addAttribute("pageName", "用户编辑");
        return "system/user/edit";
    }

    /**
     * 处理编辑
     *
     * @return
     */
    @RequestMapping(value = "/doedit", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object doedit(User user) {
        User user2 = userService.findByLoginName(user.getLoginname());
        if (user2 != null && user.getId() != user2.getId()) {
            return renderError("用户名已存在!");
        }

        try {
            //更新用户,封装到了一个事务中
            userService.updateUser(user);
        } catch (ServiceException e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("修改成功！");
    }

    /**
     * 用户分配角色
     *
     * @return
     */
    @RequestMapping(value = "/grant")
    public Object grant(Integer id, Model model) throws ControllerException {

        User user = userService.findById(id);
        if (user == null) {
            throw new ControllerException("没有这个用户");
        }

        List<Option> options = roleService.findAllRolesOptionsByUserId(id);

        model.addAttribute("roleOptions", options);

        model.addAttribute("pageName", "用户分配角色");
        model.addAttribute("user", user);

        return "system/user/grant";
    }

    /**
     * 处理角色分配资源
     *
     * @return
     */
    @RequestMapping(value = "/dogrant", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object dogrant(Integer userId, @RequestParam(value = "roleIds[]", required = false) Integer[] roleIds) {
        try {
            userService.updateRoles(userId, roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError("分配失败!");
        }
        return renderSuccess("分配成功!");
    }

    /**
     * 批量删除
     *
     * @param ids ids
     * @return
     */
    @RequestMapping(value = "/delete", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object delete(@RequestParam(value = "ids[]") Integer[] ids) {
        try {
            userService.deleteBatch(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("删除成功!");
    }
}
